#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <string>
#include "sprite.h"

static std::string graphicsDirectory;

// Returns the absolute path to the graphics directory, with
// fname appended to it
std::string gfxDir(const char *fname)
{
	char cdir[1024];
	std::string str = "";

	if(graphicsDirectory=="") {
		get_executable_name(cdir,1024);
		replace_filename(cdir,cdir, "", 1024);
		graphicsDirectory = std::string(cdir)+std::string("gfx/");
	}
	
	str = graphicsDirectory + fname;
	return (str);
}

int load_file_v(const char *fname, int attrib, void *param)
{
	std::vector<BITMAP *> *p;
	BITMAP *tmp;
	p = (std::vector<BITMAP *> *)param;
	
	
	tmp = load_bitmap(fname, NULL);
	if(tmp != NULL)
		p->push_back(tmp);
	else {
		printf("Failed to load bitmap \"%s\"\n", fname);	
		return 0;
	}
	
	printf("Loaded bitmap \"%s\" successfully\n", fname);
	
	return 0;
}

int load_file_m(const char *fname, int attrib, void *param)
{
	std::map<std::string,BITMAP *> *p;
	BITMAP *tmp;
	p = (std::map<std::string,BITMAP *> *)param;
	
	
	tmp = load_bitmap(fname, NULL);
	if(tmp != NULL) {
		(*p)[std::string(get_filename(fname))] = tmp;
	}else {
		printf("Failed to load bitmap \"%s\"\n", fname);	
		return 0;
	}
	
	printf("Loaded bitmap \"%s\" successfully : %p\n", fname, tmp);
	
	return 0;
}


void Sprite::load_directory(const char *dir, std::vector<BITMAP *>*dest)
{	for_each_file_ex(gfxDir(dir).c_str(), 0, FA_DIREC, load_file_v, dest); }

void Sprite::load_directory(const char *dir, std::map<std::string, BITMAP *>*dest)
{	for_each_file_ex(gfxDir(dir).c_str(), 0, FA_DIREC, load_file_m, dest); }


void Sprite::load_planets(void) {
    load_directory("planets/*", &pls);
}

void Sprite::load_weapons(void) {
    load_directory("weapons/*", &weaps);
}

void Sprite::load_shots(void) {
    load_directory("shots/*", &shots);
}

BITMAP *Sprite::get_random_planet(void)
{
    return(pls[rand()%pls.size()]);
}

BITMAP *Sprite::get_weapon(const char *str)
{
    return(weaps[str]);
}

BITMAP *Sprite::get_shot(const char *str)
{
    return(shots[str]);
}

void Sprite::load_sprites()
{
	std::string str;
	graphicsDirectory = "";
	
	load_planets();
	load_weapons();
	load_shots();

	player = load_bitmap(gfxDir("player0.bmp").c_str(), NULL);
	assert(player!=NULL);
}

